import { defineStore } from 'pinia'
import { useTtsaStore } from '@/store/ttsa'
import { useTost } from '@/utils/comps'
import { MODE } from '@/constants/ttsa'
import ASR from '@/libs/xmov-asr'
import ASRTc from '@/libs/tencent-asr'
import { useUIStore } from './ui'

const asr_config = {
  origin: import.meta.env.XMOV_APP_XASR_ORIGIN,
  app_id: import.meta.env.XMOV_APP_XASR_APPID,
  secret_key: import.meta.env.XMOV_APP_XASR_SECRET_KEY,
  debug: false
}

export const useAsrStore = defineStore('asrStore', () => {
  const ttsa = useTtsaStore();
  const ui = useUIStore()
  const asrService = ref(null)

  const resultText = ref('');
  const touchStatus = ref(false)
  const asring = ref(false)
  const audioId = ref(null)
  let timer = null
  const onError = (error?) => {
    console.log('error', Date.now(), error);
    if (error && ![10402, 10403].includes(error.code) && !error.stack) useTost(error?.message)
    stop()
  }

  const initAsrService = () => {
    console.log('asr-init', Date.now())
    const AsrClass = useUrlSearchParams('history')?.asrType === 'tc' ? ASRTc : ASR
    asrService.value = new AsrClass({
      ...asr_config,
      on: {
        onRecognitionStart() {
          console.log('连接已建立', Date.now());
          if (!touchStatus.value) stop()
        },
        onRecognitionResultChange(res) {
          console.log('当前这句话部分结果', Date.now(), res);
          resultText.value = asrService.value?.processText
          if (res?.voice_id) audioId.value = res.voice_id
          asrCheckText()
        },
        onSentenceEnd(res) {
          console.log('一句话识别完毕', Date.now(), res);
          resultText.value = asrService.value?.processText
          asrCheckText()
        },
        onStoped() {
          console.log('asr-stoped');
        },
        onError(error) {
          asring.value = false
          onError(error)
        },
      },
    })
  }

  const setVideo = (isStart) => {
    const video: HTMLMediaElement = document.querySelector('#ttsa video')
    if (video) {
      video.muted = isStart
      if (!isStart) video.play()
    }
  }

  const start = () => {
    console.log('asr-start', Date.now())
    console.time('asr-start');
    asrService.value.start()
      .then(() => {
        console.timeEnd('asr-start');
        asring.value = true
        resultText.value = ''
        if (!touchStatus.value) stop()
      })
      .catch((error) => {
        console.log('asr-start-error', Date.now())
        asring.value = false
        onError(error)
      })
  }

  const stop = () => {
    console.log('asr-stop', Date.now());
    asrService.value?.stop()
    asring.value = false
    setVideo(false)
    window.removeEventListener('touchend', onTouchEnd)
    window.removeEventListener('touchcancel', onTouchEnd)
    setTimeout(() => {
      send()
    }, 100)
  }

  const send = () => {
    console.log('asr-send', Date.now());
    if (touchStatus.value) {
      touchStatus.value = false
      setVideo(false)
    }
    if (resultText.value) ttsa.chat(resultText.value, { asr_sessionid: audioId.value })
    resultText.value = ''
    audioId.value = null
  }

  const asrCheckText = () => {
    if (resultText.value.length > 60) stop()
  }

  const onTouchstart = () => {
    if (asring.value) return
    console.log('touch start', Date.now());
    touchStatus.value = true
    window.addEventListener('touchend', onTouchEnd, { passive: true })
    window.addEventListener('touchcancel', onTouchEnd, { passive: true })
    if (ttsa.mode !== MODE.QA) ttsa.explainToQa()
    setVideo(true)
    closeTimer()
    timer = setTimeout(() => {
      ui.clear()
      ttsa.pause()
      initAsrService()
      start()
    }, 260)
  }

  const onTouchEnd = () => {
    console.log('touch end', Date.now());
    touchStatus.value = false
    closeTimer()
    stop()
  }

  const onTouchCancel = () => {
    console.log('touchcancel');
    onTouchEnd()
  }

  const closeTimer = () => {
    clearTimeout(timer)
    timer = null
  }

  return {
    touchStatus,
    asring,
    asrText: resultText,
    asrService,
    onTouchstart,
    onTouchEnd,
    onTouchCancel
  }
})
